

import json
import traceback
from logging import Logger
from typing import Optional

from api.httpx_client import HttpXClient


class ApiX:

    def __init__(self ,logger:Optional[Logger]):
        self.httpx_client = HttpXClient()
        # self.ip_address = "192.168.100.60"
        self.ip_address = "192.168.123.164"
        self.base_url = f"http://{self.ip_address}:8990/g1edu_motion"   #  110.252
        self.logger = logger

    def setHost(self,ip_address):
        """ 设置主机地址 """
        self.ip_address = ip_address
        self.base_url = f"http://{self.ip_address}:8990/g1edu_motion"  # 110.252


    async def sync_joints_data(self):
        """ 同步当前关节数据 """
        try:
            url = self.base_url + "/queryJoints"
            self.logger.info(f"-------sync_joints_data:{url}")
            response = await self.httpx_client.post(url=url)
            self.logger.info(f"-------sync_joints_data:{response}")
            if int(response['status']) == 200:
                return json.loads(response['data'])
            else:
                return None
        except:
            err = traceback.format_exc()
            self.logger.info(f"-------sync_joints_data:{err}")
            return None


    async def load_and_play(self, data):
        """ 下发和测试动作 """
        try:
            url = self.base_url + "/loadAndPlayMotion"
            self.logger.info(f"------url: {url} , load_and_play:{data}")
            response = await self.httpx_client.post(url=url, data=data)
            self.logger.info(f"-------load_and_play:{response}")
        except:
            err = traceback.format_exc()
            self.logger.info(f"-------load_and_play:{err}")
            return None
